import React, { useMemo, useCallback } from "react";
import {
  FlatList,
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ActivityIndicator,
  Platform,
} from "react-native";
import HighlightText from "../../../HighLightText/index";
import { Feather, Ionicons } from "@expo/vector-icons";
import {
  Contact,
  SearchResultItem,
  SearchResultListProps,
} from "../../types/index";
const TwitterTheme = {
  colors: {
    primary: "#1D9BF0",
    background: "#FFFFFF",
    border: "#E0E0E0",
    textPrimary: "#0F1419",
    textSecondary: "#536471",
    hover: "#F5F8FA",
    icon: "#536471",
  },
  typography: {
    regular: {
      fontSize: 15,
      fontFamily: Platform.select({
        ios: "SFProText-Regular",
        android: "Roboto",
      }),
      lineHeight: 20,
    },
    medium: {
      fontSize: 15,
      fontFamily: Platform.select({
        ios: "SFProText-Medium",
        android: "Roboto-Medium",
      }),
      lineHeight: 20,
    },
  },
  spacing: {
    itemPadding: 16,
    iconSize: 24,
  },
};
const SearchResultList: React.FC<SearchResultListProps> = ({
  searchText,
  contacts,
  groupChats,
  isLoading = false,
  onItemPress,
  onAddNew,
}) => {
  const searchResults = useMemo<SearchResultItem[]>(() => {
    if (!searchText.trim()) return [];
    const lowerText = searchText.trim().toLowerCase();
    const results: SearchResultItem[] = [];
    // 联系人分组搜索
    const groupMap = new Map<string, Contact[]>();
    contacts.forEach((contact) => {
      const isMatch =
        contact.name.toLowerCase().includes(lowerText) ||
        contact.group.toLowerCase().includes(lowerText);
      if (isMatch) {
        const existing = groupMap.get(contact.group) || [];
        groupMap.set(contact.group, [...existing, contact]);
      }
    });

    groupMap.forEach((contacts, group) => {
      results.push({
        type: "contact-group",
        id: `contact-group-${group}`,
        title: group,
        subtitle: contacts.map((c) => c.name).join(", "),
        meta: `${contacts.length} contacts`,
        data: contacts,
      });
    });

    // 群聊搜索（仅在无联系人结果时触发）
    if (results.length === 0) {
      groupChats
        .filter((group) => group.name.toLowerCase().includes(lowerText))
        .forEach((group) => {
          results.push({
            type: "group-chat",
            id: `group-${group.id}`,
            title: group.name,
            meta: `${group.members} members`,
            data: group,
          });
        });
    }
    // 新增条目
    if (results.length === 0 && !isLoading) {
      results.push({
        type: "new-entry",
        id: `new-${searchText}`,
        title: `Add ${searchText} as a new Friend`,
      });
    }

    return results;
  }, [searchText, contacts, groupChats, isLoading]);

  const handlePress = useCallback(
    (item: SearchResultItem) => {
      if (item.type === "new-entry") {
        onAddNew?.(searchText);
      } else {
        onItemPress?.(item);
      }
    },
    [onAddNew, onItemPress, searchText]
  );

  const renderItem = ({ item }: { item: SearchResultItem }) => (
    <TouchableOpacity
      style={styles.itemContainer}
      onPress={() => handlePress(item)}
      accessibilityRole="button"
      accessibilityLabel={`${item.type} item: ${item.title}`}
    >
      <View style={styles.iconContainer}>
        {item.type === "contact-group" ? (
          <Feather name="users" size={20} color={TwitterTheme.colors.icon} />
        ) : item.type === "group-chat" ? (
          <Ionicons name="people" size={20} color={TwitterTheme.colors.icon} />
        ) : (
          <Feather name="plus" size={20} color={TwitterTheme.colors.icon} />
        )}
      </View>

      <View style={styles.textContainer}>
        <View style={styles.titleRow}>
          <HighlightText
            text={item.title}
            searchText={searchText}
            highlightStyle={{ color: TwitterTheme.colors.primary }}
          />
          {item.type === "contact-group" && (
            <Feather
              name="check-circle"
              size={16}
              color={TwitterTheme.colors.primary}
              style={styles.verifiedIcon}
            />
          )}
        </View>
        {item.subtitle && (
          <HighlightText text={item.subtitle || ""} searchText={searchText} />
        )}
        <Text>{item.meta}</Text>
      </View>

      {item.type === "new-entry" && (
        <Feather
          name="arrow-up-left"
          size={16}
          color={TwitterTheme.colors.textSecondary}
          style={styles.actionIcon}
        />
      )}
    </TouchableOpacity>
  );

  return (
    <FlatList
      data={searchResults}
      renderItem={renderItem}
      keyExtractor={(item) => item.id}
      keyboardDismissMode="on-drag"
      keyboardShouldPersistTaps="handled"
      ListEmptyComponent={
        isLoading ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator color={TwitterTheme.colors.primary} />
          </View>
        ) : (
          <View style={styles.emptyContainer}>
            <Text style={styles.emptyText}>No results found</Text>
          </View>
        )
      }
      ItemSeparatorComponent={() => <View style={styles.separator} />}
      contentContainerStyle={styles.listContent}
    />
  );
};

const styles = StyleSheet.create({
  itemContainer: {
    flexDirection: "row",
    alignItems: "center",
    padding: TwitterTheme.spacing.itemPadding,
    backgroundColor: TwitterTheme.colors.background,
  },
  iconContainer: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: TwitterTheme.colors.hover,
    justifyContent: "center",
    alignItems: "center",
    marginRight: 12,
  },
  textContainer: {
    flex: 1,
  },
  titleRow: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 2,
  },
  titleText: {
    ...TwitterTheme.typography.medium,
    color: TwitterTheme.colors.textPrimary,
    marginRight: 4,
  },
  subtitleText: {
    ...TwitterTheme.typography.regular,
    color: TwitterTheme.colors.textSecondary,
    marginBottom: 2,
  },
  metaText: {
    ...TwitterTheme.typography.regular,
    color: TwitterTheme.colors.textSecondary,
    fontSize: 13,
  },
  verifiedIcon: {
    marginLeft: 4,
  },
  actionIcon: {
    marginLeft: "auto",
    paddingLeft: 16,
  },
  separator: {
    height: 1,
    backgroundColor: TwitterTheme.colors.border,
    marginLeft: 68,
  },
  listContent: {
    paddingBottom: 48,
  },
  loadingContainer: {
    padding: 24,
    alignItems: "center",
  },
  emptyContainer: {
    padding: 24,
    alignItems: "center",
  },
  emptyText: {
    ...TwitterTheme.typography.regular,
    color: TwitterTheme.colors.textSecondary,
  },
});

export default SearchResultList;
